from rest_framework import serializers
from fdfs_client.client import Fdfs_client
from django.conf import settings

from goods.models import SKUImage, SKU
from celery_tasks.detail_static.tasks import generate_static_sku_detail_html


class SKUImageSerializer(serializers.ModelSerializer):
    sku_id = serializers.PrimaryKeyRelatedField(read_only=True)

    class Meta:
        model = SKUImage
        fields = '__all__'

    def create(self, validated_data):
        # 向fdfs存储图片
        client = Fdfs_client(settings.FDFS_CONFIG)
        res = client.upload_by_buffer(validated_data.get('image').read())
        if res['Status'] != 'Upload successed.':  # 存储失败
            return serializers.ValidationError({'errmsg': '存储图片失败'})

        # 保存数据库
        img = SKUImage.objects.create(sku=validated_data.get('sku'), image=res.get('Remote file_id'))

        generate_static_sku_detail_html.delay(img.sku.id)

        # 返回结果
        return img

    def update(self, instance, validated_data):
        client = Fdfs_client(settings.FDFS_CONFIG)
        res = client.upload_by_buffer(validated_data.get('image').read())
        if res['Status'] != 'Upload successed.':  # 存储失败
            return serializers.ValidationError({'errmsg': '存储图片失败'})

        instance.image = res.get('Remote file_id')
        instance.save()

        generate_static_sku_detail_html.delay(instance.sku.id)

        return instance


class SKUSerializer(serializers.ModelSerializer):
    class Meta:
        model = SKU
        fields = ('id', 'name')
